package com.app.conf;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import lombok.extern.slf4j.Slf4j;

/**
 * 数据库备份与还原
 * @author ccit
 *
 */
@Slf4j
public class DbOperate {

    /**
     * 用户名
     */
    private static String root = "remote";

    /**
     * 密码
     */
    private static String pwd = "123456";

    /**
     * 数据库名字
     */
    private static String dbName = "office_manage";

    /**
     * 备份路径
     */
    private static String backPath = "E:/www/backUp";
//	private static String backPath = "/home/";

    /**
     * 恢复路径
     */
    private static String filePath = "D:/recover/back.sql";
//	private static String filePath = "/home/back.sql";

    /**
     * ip
     *
     * @param args
     */
    private static String ip = "127.0.0.1";


    public static void main(String[] args) throws Exception {
        //1.本地需安装mysql
        //2.配置mysql 环境变量
			dbBackUp(); // 备份方法
//        dbRestore();//还原方法   还原时  需要提前创建了数据库
    }


    /**
     * 备份数据库db
     */
    public static void dbBackUp() throws Exception {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd-HH-mm-sss");
        String backName = dateFormat.format(date) + ".sql";
        String pathSql = "";
        //输出流文件
        File fileSql = new File(pathSql);
        try {
            //判断系统
            String osName = System.getProperties().getProperty("os.name");
            if (osName.equals("Linux")) {
                pathSql = "LBackPath" + backName;
            } else {
                pathSql = "WBackPath" + backName;

            }

            //输出流文件
            fileSql = new File(pathSql);
            //创建备份sql文件
            if (!fileSql.exists()) {
                fileSql.createNewFile();
            }

            //mysqldump -hlocalhost -uroot -p123456 db > /home/back.sql  //整个库进行备份sql文件
            //mysqldump -hlocalhost -uroot -p123456 数据库名  数据表名 > /home/back.sql  单张表备份sql文件
            StringBuffer sb = new StringBuffer();
            sb.append("mysqldump");
            sb.append(" -h" + ip);
            sb.append(" -u" + root);
            sb.append(" -p" + pwd);
            sb.append(" " + dbName + " ");
            sb.append("-r");//java中必须使用"-r"替代">"
            sb.append(pathSql);

            Process process = null;
            //判断系统
            if (osName.equals("Linux")) {
                BufferedReader bufferedReader = null;
                PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileSql), "utf8"));
                process = Runtime.getRuntime().exec(" mysqldump -h" + ip + " -u" + root + " -p" + pwd + " --set-charset=UTF8 " + dbName + " -r /home/back.sql");
                InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
                bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    printWriter.println(line);
                }
                printWriter.flush();
                log.info("-==[ 备份结束！ ]==-");
            } else {
                System.out.println("cmd命令为：" + "cmd /c " + sb.toString());
                process = Runtime.getRuntime().exec("cmd /c " + sb.toString());//执行语句
            }
            process.waitFor();//等待上述命令执行完毕后打印下面log

            //输出错误信息
            InputStream is = process.getErrorStream();
            InputStreamReader isr = new InputStreamReader(is, "gbk");//读取
            System.out.println(isr.getEncoding());
            BufferedReader bufr = new BufferedReader(isr);//缓冲
            String line = null;
            while ((line = bufr.readLine()) != null) {
                System.out.println("error:" + line);
            }
            isr.close();
            log.info("数据库备份结束，备份结果：{}", process.exitValue() == 0 ? "success" : "fail");
        } catch (Exception e){
            System.out.println(e);
        }

    }
    /**
     * 恢复数据库
     * mysql -hlocalhost -uroot -proot dbname < /home/back.sql
     */
    public static void dbRestore(){
        StringBuilder sb = new StringBuilder();
        sb.append("mysql");
        sb.append(" -h"+ip);
        sb.append(" -u"+root);
        sb.append(" -p"+pwd);
        sb.append(" "+dbName+" <");
        sb.append(filePath);
        System.out.println("cmd命令为："+sb.toString());
        Runtime runtime = Runtime.getRuntime();
        System.out.println("开始还原数据");
        try {
            Process process = runtime.exec("cmd /c"+sb.toString());

            //输出错误信息
            FileInputStream errorStream = (FileInputStream)process.getErrorStream();
            InputStreamReader isr = new InputStreamReader(errorStream,"gbk");//读取
            System.out.println(isr.getEncoding());
            BufferedReader bufr = new BufferedReader(isr);//缓冲
            String line = null;
            while((line =bufr.readLine())!=null) {
                System.out.println("error:"+line);
            }
            isr.close();


            InputStream is = process.getInputStream();
            BufferedReader bf = new BufferedReader(new InputStreamReader(is,"utf8"));
            line = null;
            while ((line=bf.readLine())!=null){
                System.out.println(line);
            }
            is.close();
            bf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("还原成功！");
    }

}
